package Q5;

//tcp 协议的编程模型实现多人同时在线聊天和传输文件，要求每个客户端将发 送的聊天内容和文件发送到服务器，服务器接收到后转发给当前所有在线的客户端

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Arrays;
import Q5.ServerTool;

public class TalkServer {
    private static final int MAX_SOCKET = 5;
    public static Socket[] sockets = new Socket[MAX_SOCKET];
    public static int socketNum;
    static {
        Arrays.fill(sockets, null);
        socketNum = 0;
    }

    public static void main(String[] args) {
        ServerSocket ss = null;
        BufferedReader br = null;


        try {
            //创建socket
            ss = new ServerSocket(8888);
            ServerTool.creatLocalStorage();
            System.out.println("等待用户连接");
            //输入输出流
            while(socketNum < MAX_SOCKET) {
                //等用户加入群组后获取用户名
                sockets[socketNum] = ss.accept();
                br = new BufferedReader(new InputStreamReader(sockets[socketNum].getInputStream()));
                String name = br.readLine();
                System.out.println(name + "加入群聊");
                //增加线程
                ServerThreadRunnable myRunnable = new ServerThreadRunnable(name, socketNum);
                Thread thread = new Thread (myRunnable);
                thread.start();
                socketNum++;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭
            try {
                if (br != null) {
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (ss != null) {
                    ss.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
